package cn.com.acca.ma.service.impl;

import java.awt.Color;
import java.awt.Paint;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickMarkPosition;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.SegmentedTimeline;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;

import cn.com.acca.ma.common.util.DateUtil;
import cn.com.acca.ma.common.util.PropertiesUtil;
import cn.com.acca.ma.common.util.StringUtil;
import cn.com.acca.ma.jfreechart.util.MySpiderWebPlot;
import cn.com.acca.ma.model.Board;
import cn.com.acca.ma.model.BoardIndex;
import cn.com.acca.ma.service.BoardIndexService;

public class BoardIndexServiceImpl extends BaseServiceImpl<BoardIndexServiceImpl,BoardIndex> implements BoardIndexService {

	public BoardIndexServiceImpl() {
		super();
	}

	/**
	 * 计算BOARD_INDEX表中的数据
	 */
	public void calculateBoardIndex() {
		boardIndexDao.calculateBoardIndex();
	}
	
	/**
	 * 计算BOARD_INDEX表中的FIVE_DAY_RATE字段和TEN_DAY_RATE字段
	 */
	public void calculateAllBoardIndexFiveAndTenDayRate(){
		boardIndexDao.calculateAllBoardIndexFiveAndTenDayRate();
	}

	/**
	 * 计算BOARD_INDEX表中某一日的FIVE_DAY_RATE字段和TEN_DAY_RATE字段
	 * @param multithreading
	 */
	public void writeBoardIndexFiveAndTenDayRateByDate(boolean multithreading){
		String boardDate = PropertiesUtil.getValue(BOARD_INDEX_PROPERTIES,"boardIndex.fiveAndTenDayRate.date");
		boardIndexDao.writeBoardIndexFiveAndTenDayRateByDate(multithreading, boardDate);
	}
	
	/**
     * 计算BOARD_INDEX表的UP_DOWN_PERCENTAGE字段
     */
    public void calculateBoardIndexUpDownPercentage(){
    	boardIndexDao.calculateBoardIndexUpDownPercentage();
    }

	/**
	 * 计算BOARD_INDEX表中某一日的UP_DOWN_PERCENTAGE字段
	 * @param multithreading
	 */
	public void writeBoardIndexUpDownPercentageByDate(boolean multithreading){
    	String boardDate = PropertiesUtil.getValue(BOARD_INDEX_PROPERTIES,"boardIndex.up_down_percent.date");
		boardIndexDao.writeBoardIndexUpDownPercentageByDate(multithreading, boardDate);
    }
    
    /**
     * 计算BOARD_INDEX表的UP_DOWN_RANK字段
     */
    public void calculateBoardIndexUpDownRank(){
    	boardIndexDao.calculateBoardIndexUpDownRank();
    }

	/**
	 * 计算BOARD_INDEX表中某一日的UP_DOWN_RANK字段
	 * @param multithreading
	 */
	public void writeBoardIndexUpDownRankByDate(boolean multithreading){
    	String boardDate = PropertiesUtil.getValue(BOARD_INDEX_PROPERTIES,"boardIndex.up_down_rank.date");
		boardIndexDao.writeBoardIndexUpDownRankByDate(multithreading, boardDate);
    }

	/**
	 * 创建板块K线图
	 * @param multithreading
	 */
	public void createBoardPicture(boolean multithreading) {
		String boardBeginDate = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES,"boardIndexPicture.beginDate");
		String boardEndDate = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES,"boardIndexPicture.endDate");
		String boardTimeInterval = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.timeInterval");
		
		//删除src/main/resources/picture/board_index目录下的所有图片文件
		deleteAllFiles(PICTURE_PATH+"/board_index");
		
		List<BigDecimal> allBoardIdList = boardDao.getAllBoardId(multithreading);
		
		//根据版块board_id绘制不同版块的图片
		for(int i=0;i<allBoardIdList.size();i++){
			paintBoardPicture(multithreading, boardBeginDate, boardEndDate, allBoardIdList.get(i).toString(),boardTimeInterval);
		}
	}

	/**
	 * 返回从开始日期beginDate到结束日期endDate之间的BoardIndex数据
	 */
	public List<BoardIndex> getBoardIndexWithinDate(String beginDate,String endDate, String boardId) {
		return boardIndexDao.getBoardIndexWithinDate(beginDate, endDate, boardId);
	}
	
	/**
	 * 根据开始时间，结束时间和板块ID绘制板块K线图
	 * @param boardBeginDate 开始时间
	 * @param boardEndDate 结束时间
	 * @param boardId 板块ID
	 * @param timeInterval 图片右边的间隔
	 */
	@SuppressWarnings({ "deprecation", "static-access" })
	public void paintBoardPicture(boolean multithreading, String boardBeginDate, String boardEndDate, String boardId, String timeInterval){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		double kLineMaxValue = Double.MIN_VALUE;// 设置K线数据当中的最大值
		double kLineMinValue = Double.MAX_VALUE;// 设置K线数据当中的最小值
		double amountMaxValue = Double.MIN_VALUE;// 设置成交量的最大值
		double amountMinValue = Double.MAX_VALUE;// 设置成交量的最低值
		
		List<BoardIndex> boardIndexList = getBoardIndexWithinDate(boardBeginDate, boardEndDate, boardId);
		/* 添加这个判断是为了解决一个bug：BOARD表中ID字段为49的记录（军工）的STOCK_AMOUNT字段为0，这会导致
		 * 下面的代码抛出数组下表越界异常，因此在这个地方跳过所有STOCK_AMOUNT字段为0的板块 */
		if(boardIndexList.size()==0){
			return;
		}
		
		// 获取日期，开盘价，最高价，最低价和收盘价
		OHLCSeries seriesPrice = new OHLCSeries("K线图");// 高开低收数据序列，股票K线图的四个数据，依次是开，高，低，收
		seriesPrice.clear();
		for (int i = 0; i < boardIndexList.size(); i++) {
			seriesPrice.add(new Day(DateUtil.getDateFromDate(boardIndexList.get(i).getDate()),
					DateUtil.getMonthFromDate(boardIndexList.get(i).getDate()),
					DateUtil.getYearFromDate(boardIndexList.get(i).getDate())),
					boardIndexList.get(i).getOpenPrice().doubleValue(),
					boardIndexList.get(i).getHighestPrice().doubleValue(),
					boardIndexList.get(i).getLowestPrice().doubleValue(),
					boardIndexList.get(i).getClosePrice().doubleValue());
		}
		for(int i=1;i<=100;i++){
			seriesPrice.add(new Day((0+i)%28+1,
					(0+i)%12+1,
					1900+i),
					1,
					1,
					1,
					1);
		}
		final OHLCSeriesCollection priceSeriesCollection = new OHLCSeriesCollection();//保留K线数据的数据集，必须申明为final，后面要在匿名内部类里面用到
		priceSeriesCollection.addSeries(seriesPrice);
		
		// 获取成交量
		TimeSeries seriesAmount=new TimeSeries("");//对应时间成交量数据
		seriesAmount.clear();
		for(int i=0;i<boardIndexList.size();i++){
			seriesAmount.add(new Day(DateUtil.getDateFromDate(boardIndexList.get(i).getDate()),
					DateUtil.getMonthFromDate(boardIndexList.get(i).getDate()),
					DateUtil.getYearFromDate(boardIndexList.get(i).getDate())),
					boardIndexList.get(i).getAmount());
		}
		for(int i=1;i<=100;i++){
			seriesAmount.add(new Day((0+i)%28+1,
					(0+i)%12+1,
					1900+i),
					1);
		}
		TimeSeriesCollection amountSeriesCollection=new TimeSeriesCollection();//保留成交量数据的集合
		amountSeriesCollection.addSeries(seriesAmount);
		
		//获取K线数据的最高值和最低值
		int seriesCountPrice = priceSeriesCollection.getSeriesCount();//一共有多少个序列，目前为一个
		for (int i = 0; i < seriesCountPrice; i++) {
			int itemCount = priceSeriesCollection.getItemCount(i);//每一个序列有多少个数据项
			for (int j = 0; j < itemCount; j++) {
				if (kLineMaxValue < priceSeriesCollection.getHighValue(i, j)) {//取第i个序列中的第j个数据项的最大值
					kLineMaxValue = priceSeriesCollection.getHighValue(i, j);
				}
				if (kLineMinValue > priceSeriesCollection.getLowValue(i, j)) {//取第i个序列中的第j个数据项的最小值
					kLineMinValue = priceSeriesCollection.getLowValue(i, j);
				}
			}
		}
		//获取最高值和最低值
		int seriesCountAmount = amountSeriesCollection.getSeriesCount();//一共有多少个序列，目前为一个
		for (int i = 0; i < seriesCountAmount; i++) {
			int itemCount = amountSeriesCollection.getItemCount(i);//每一个序列有多少个数据项
			for (int j = 0; j < itemCount; j++) {
				if (amountMaxValue < amountSeriesCollection.getYValue(i,j)) {//取第i个序列中的第j个数据项的值
					amountMaxValue = amountSeriesCollection.getYValue(i,j);
				}
				if (amountMinValue > amountSeriesCollection.getYValue(i, j)) {//取第i个序列中的第j个数据项的值
					amountMinValue = amountSeriesCollection.getYValue(i, j);
				}
			}
		}
		
		final CandlestickRenderer candlestickRender=new CandlestickRenderer();//设置K线图的画图器，必须申明为final，后面要在匿名内部类里面用到
		candlestickRender.setUseOutlinePaint(true); //设置是否使用自定义的边框线，程序自带的边框线的颜色不符合中国股票市场的习惯
		candlestickRender.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_AVERAGE);//设置如何对K线图的宽度进行设定
		candlestickRender.setAutoWidthGap(0.001);//设置各个K线图之间的间隔
		candlestickRender.setUpPaint(Color.RED);//设置股票上涨的K线图颜色
		candlestickRender.setDownPaint(Color.GREEN);//设置股票下跌的K线图颜色
		DateAxis x1Axis=new DateAxis();//设置x轴，也就是时间轴
		x1Axis.setAutoRange(false);//设置不采用自动设置时间范围
		try{
			x1Axis.setRange(dateFormat.parse(StringUtil.convertDateStringByFormat(boardBeginDate,"-")),dateFormat.parse(StringUtil.convertDateStringByFormat(String.valueOf(Integer.parseInt(timeInterval)+1), "-")));//设置时间范围，注意时间的最大值要比已有的时间最大值要多一天
		}catch(Exception e){
			e.printStackTrace();
		}
		x1Axis.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());//设置时间线显示的规则，用这个方法就摒除掉了周六和周日这些没有交易的日期(很多人都不知道有此方法)，使图形看上去连续
		x1Axis.setAutoTickUnitSelection(false);//设置不采用自动选择刻度值
		x1Axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);//设置标记的位置
		x1Axis.setStandardTickUnits(DateAxis.createStandardDateTickUnits());//设置标准的时间刻度单位
		x1Axis.setTickUnit(new DateTickUnit(DateTickUnit.DAY,7));//设置时间刻度的间隔，一般以周为单位
		x1Axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));//设置显示时间的格式
		NumberAxis y1Axis=new NumberAxis();//设定y轴，就是数字轴
		y1Axis.setAutoRange(false);//不使用自动设定范围
		y1Axis.setRange(kLineMinValue*0.9, kLineMaxValue*1.1);//设定y轴值的范围，比最低值要低一些，比最大值要大一些，这样图形看起来会美观些
		y1Axis.setTickUnit(new NumberTickUnit((kLineMaxValue*1.1-kLineMinValue*0.9)/10));//设置刻度显示的密度
		XYPlot plot1=new XYPlot(priceSeriesCollection,x1Axis,y1Axis,candlestickRender);//设置画图区域对象
	  
		XYBarRenderer xyBarRender=new XYBarRenderer(){
			private static final long serialVersionUID = 1L;//为了避免出现警告消息，特设定此值
			public Paint getItemPaint(int i, int j){//匿名内部类用来处理当日的成交量柱形图的颜色与K线图的颜色保持一致
				if(priceSeriesCollection.getCloseValue(i,j)>priceSeriesCollection.getOpenValue(i,j)){//收盘价高于开盘价，股票上涨，选用股票上涨的颜色
					return candlestickRender.getUpPaint();
				}else{
					return candlestickRender.getDownPaint();
				}
			}
		};
		
		xyBarRender.setMargin(0.1);//设置柱形图之间的间隔
		NumberAxis y2Axis=new NumberAxis();//设置Y轴，为数值,后面的设置，参考上面的y轴设置
		y2Axis.setAutoRange(false);
		y2Axis.setRange(amountMinValue*0.9, amountMaxValue*1.1);
		y2Axis.setTickUnit(new NumberTickUnit((amountMaxValue*1.1-amountMinValue*0.9)/4));
		XYPlot plot2=new XYPlot(amountSeriesCollection,null,y2Axis,xyBarRender);//建立第二个画图区域对象，主要此时的x轴设为了null值，因为要与第一个画图区域对象共享x轴
		CombinedDomainXYPlot combineddomainxyplot = new CombinedDomainXYPlot(x1Axis);//建立一个恰当的联合图形区域对象，以x轴为共享轴
		combineddomainxyplot.add(plot1, 2);//添加图形区域对象，后面的数字是计算这个区域对象应该占据多大的区域2/3
	    combineddomainxyplot.add(plot2, 1);//添加图形区域对象，后面的数字是计算这个区域对象应该占据多大的区域1/3
	    combineddomainxyplot.setGap(10);//设置两个图形区域对象之间的间隔空间
	    JFreeChart chart = new JFreeChart(boardDao.findBoardNameById(multithreading, boardIndexList.get(0).getBoardId()), JFreeChart.DEFAULT_TITLE_FONT, combineddomainxyplot, false);
	    
	    try {
			FileOutputStream fos = new FileOutputStream(PICTURE_PATH+"board_index/"+boardBeginDate+"-"+boardEndDate+"_"+boardDao.findBoardNameById(multithreading, boardIndexList.get(0).getBoardId())+PICTURE_FORMAT);
			// 将统计图标输出成JPG文件
			ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
					1, // JPEG图片的质量，0~1之间
					chart, // 统计图标对象
					this.imageWidth, // 宽
					this.IMAGE_HEIGHT, // 高
					null // ChartRenderingInfo 信息
					);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据日期，计算board_index表中某一日的记录
	 * @param multithreading
	 */
	public void writeBoardIndexByDate(boolean multithreading){
		String boardIndexDate = PropertiesUtil.getValue(BOARD_INDEX_PROPERTIES,"boardIndex.date");
		boardIndexDao.writeBoardIndexByDate(multithreading, boardIndexDate);
	}
	
	/**
	 * 删除指定目录下的所有文件
	 * @param path
	 */
	public void deleteAllFiles(String path){
		File file=new File(path);
		if(file.isDirectory()){
			String[] fileArray=file.list();
			for(int i=0;i<fileArray.length;i++){
				File pictureFile=new File(path+"/"+fileArray[i]);
				pictureFile.delete();
			}
		}
	}
	
	/**
	 * 查询某一天涨停的股票属于哪些板块
	 */
	public void findLimitUpStockBoardByDate(){
		String limitUpStockBoard = PropertiesUtil.getValue(REPORT_PROPERTIES,"report.limitupStock.inBoard.date");
		boardIndexDao.findLimitUpStockBoardByDate(limitUpStockBoard);
	}

	/**
	 * 将List类型转换为String类型
	 * @param list
	 * @return
	 */
	@Override
	public String listToString(List list) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 创建蜘蛛雷达图
	 * @param multithreading
	 */
	public void createSpiderWebPlotPicture(boolean multithreading) {
		FileOutputStream fos = null;
		try {
			MySpiderWebPlot spiderwebplot = new MySpiderWebPlot(this.getDefaultCategoryDatasetForSpiderWebPlotPicture(multithreading));
			JFreeChart jfreechart = new JFreeChart("Limit up Stock in Each Board",TextTitle.DEFAULT_FONT, spiderwebplot, false);
			LegendTitle legendtitle = new LegendTitle(spiderwebplot);
			legendtitle.setPosition(RectangleEdge.BOTTOM);
			jfreechart.addSubtitle(legendtitle);
			fos = new FileOutputStream(PICTURE_PATH+ "spider_web/"+ PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES,"boardIndexPicture.spiderWeb.date") + PICTURE_FORMAT);

			// 将统计图标输出成JPG文件
			ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
					1, // JPEG图片的质量，0~1之间
					jfreechart, // 统计图标对象
					1000, // 宽
					1000,// 宽
					null // ChartRenderingInfo 信息
					);
			fos.close();
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 为创建蜘蛛雷达图而获取数据
	 * @param multithreading
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public DefaultCategoryDataset getDefaultCategoryDatasetForSpiderWebPlotPicture(boolean multithreading) {
		Date boardIndexPictureDate = DateUtil.stringToDate(PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES,"boardIndexPicture.spiderWeb.date"));
		BigDecimal boardIndexPictureDateNumber = new BigDecimal(PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES,"boardIndexPicture.spiderWeb.dateNumber"));
		BigDecimal boradIndexPictureLimitRate = new BigDecimal(PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES,"boardIndexPicture.spiderWeb.limitRate"));

		DefaultCategoryDataset dataset = new DefaultCategoryDataset();

		List<HashMap> list = boardIndexDao.findDataForSpiderWebPlot(multithreading, boardIndexPictureDate, boardIndexPictureDateNumber,boradIndexPictureLimitRate);
		for (HashMap hashMap : list) {
			dataset.addValue((Number) hashMap.get("stockAmount"),(Date) hashMap.get("boardDate"), boardDao.findBoardNameById(multithreading, (BigDecimal) hashMap.get("boardId")));
		}
		return dataset;
	}

	/**
	 * 创建板块收盘价图
	 * @param multithreading
	 */
	public void createAllBoardIndexClosePicture(boolean multithreading){
		// 创建最近10年的图
		String beginDateTenYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.tenYear.close.beginDate");
		String endDateTenYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.tenYear.close.endDate");
		this.paintAllBoardIndexClosePicture(multithreading, beginDateTenYear, endDateTenYear, true);
		
		// 创建半年的图
		String beginDateHalfYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.halfYear.close.beginDate");
		String endDateHalfYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.halfYear.close.endDate");
		this.paintAllBoardIndexClosePicture(multithreading, beginDateHalfYear, endDateHalfYear, false);
	}

	/**
	 * 根据开始日期和结束日期创建板块收盘价图。分别用来创建最近10年的图和半年的图
	 * @param multithreading
	 * @param beginDate
	 * @param endDate
	 * @param flag 创建最近10年图时，flag为true，图片名称中有all；创建半年图时，flag为false，图片名称中没有all
	 */
	@SuppressWarnings("deprecation")
	public void paintAllBoardIndexClosePicture(boolean multithreading, String beginDate, String endDate, boolean flag){
		// 获取数据
		List<String> dateList = boardIndexDao.getDateByConditionForAllBoardClose(multithreading, beginDate, endDate);
		List<Board> boardList = boardDao.getAllBoard(multithreading);
		int boardNumber = boardList.size();

		TimeSeries[] boardSeries = boardIndexDao.getBoardCloseByDateAndId(multithreading, boardNumber, boardList, dateList);
		TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();

		for(int i=0;i<boardSeries.length;i++){
			timeSeriesCollection.addSeries(boardSeries[i]);
		}

		JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("All Board Index Close", 
				"Date","Index", timeSeriesCollection, true, true, true);
		jfreechart.setBackgroundPaint(Color.white);
		XYPlot xyplot = (XYPlot) jfreechart.getPlot();
		xyplot.setBackgroundPaint(Color.lightGray);
		xyplot.setDomainGridlinePaint(Color.white);
		xyplot.setRangeGridlinePaint(Color.white);
		xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
		xyplot.setDomainCrosshairVisible(true);
		xyplot.setRangeCrosshairVisible(true);
		org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot.getRenderer();
		if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
			XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer;
			xylineandshaperenderer.setBaseShapesVisible(true);
			xylineandshaperenderer.setBaseShapesFilled(true);
		}
		DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
		dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

		try {
			FileOutputStream fos = new FileOutputStream(PICTURE_PATH+"board_index_close/"+beginDate+"-"+endDate+(flag?"_all":"")+PICTURE_FORMAT);
			// 将统计图标输出成JPG文件
			ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
					1, // JPEG图片的质量，0~1之间
					jfreechart, // 统计图标对象
					1800, // 宽
					1000,// 宽
					null // ChartRenderingInfo 信息
					);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建日线级别板块的5日和10的涨跌幅度图
	 * @param multithreading
	 */
	public void createAllBoardIndexFiveAndTenDayRatePicture(boolean multithreading){
		// 创建最近10年的图
		String beginDateTenYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.tenYear.fiveAndTenRate.beginDate");
		String endDateTenYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.tenYear.fiveAndTenRate.endDate");
		this.paintAllBoardIndexFiveAndTenDayRatePicture(multithreading, beginDateTenYear, endDateTenYear, true);
		
		// 创建半年的图
		String beginDateHalfYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.halfYear.fiveAndTenRate.beginDate");
		String endDateHalfYear = PropertiesUtil.getValue(BOARD_INDEX_PICTURE_PROPERTIES, "boardIndexPicture.halfYear.fiveAndTenRate.endDate");
		this.paintAllBoardIndexFiveAndTenDayRatePicture(multithreading, beginDateHalfYear, endDateHalfYear, false);
	}

	/**
	 * 根据开始日期和结束日期创建所有板块的5日和10的涨跌幅度图。分别用来创建最近10年的图和半年的图
	 * @param multithreading
	 * @param beginDate
	 * @param endDate
	 * @param flag 创建最近2年图时，flag为true，图片名称中有all；创建半年图时，flag为false，图片名称中没有all
	 */
	@SuppressWarnings({ "rawtypes", "deprecation", "static-access" })
	public void paintAllBoardIndexFiveAndTenDayRatePicture(boolean multithreading, String beginDate, String endDate, boolean flag){
		List list = boardIndexDao.getFiveAndTenDayRateWithinDate(multithreading, beginDate, endDate);
		
		JFreeChart jfreechart;

		TimeSeries fiveDayRateSeries = new TimeSeries("Board Index - Five Day Rate",org.jfree.data.time.Day.class);
		TimeSeries tenDayRateSeries = new TimeSeries("Board Index - Ten Day Rate",org.jfree.data.time.Day.class);
		TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
		
		for (int i = 0; i < list.size(); i++) {
			Object[] object=(Object[]) list.get(i);
			int year = DateUtil.getYearFromDate(((Date)object[0]));
			int month = DateUtil.getMonthFromDate(((Date)object[0]));
			int day = DateUtil.getDateFromDate(((Date)object[0]));
			fiveDayRateSeries.add(new Day(day, month, year),Double.parseDouble(object[1].toString()));
			tenDayRateSeries.add(new Day(day, month, year),Double.parseDouble(object[2].toString()));
		}
		
		timeSeriesCollection.addSeries(fiveDayRateSeries);
		timeSeriesCollection.addSeries(tenDayRateSeries);

		jfreechart = ChartFactory.createTimeSeriesChart("Board Index and Five Day Rate of All Board Index", 
				"Date","Five Day Rate & Ten Day Rate", timeSeriesCollection, true, true, true);
		jfreechart.setBackgroundPaint(Color.white);
		XYPlot xyplot = (XYPlot) jfreechart.getPlot();
		xyplot.setBackgroundPaint(Color.lightGray);
		xyplot.setDomainGridlinePaint(Color.white);
		xyplot.setRangeGridlinePaint(Color.white);
		xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
		xyplot.setDomainCrosshairVisible(true);
		xyplot.setRangeCrosshairVisible(true);
		org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot.getRenderer();
		if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
			XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer;
			xylineandshaperenderer.setBaseShapesVisible(true);
			xylineandshaperenderer.setBaseShapesFilled(true);
		}
		DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
		dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

		try {
			FileOutputStream fos = new FileOutputStream(PICTURE_PATH+"board_index_five_ten_day_rate/"+beginDate+"-"+endDate+(flag?"_all":"")+PICTURE_FORMAT);
			// 将统计图标输出成JPG文件
			ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
					1, // JPEG图片的质量，0~1之间
					jfreechart, // 统计图标对象
					this.imageWidth, // 宽
					this.IMAGE_HEIGHT, // 高
					null // ChartRenderingInfo 信息
					);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*********************************************************************************************************************
	 * 
	 * 									                                              实验
	 * 
	 *********************************************************************************************************************/
	/**
	 * 实验图表
	 */
	@SuppressWarnings("rawtypes")
	public void testPicture2(){
		String beginDate="20150601";
		String endDate="20150605";
		
		// 用于获取并存储所有板块的ID
		List<BigDecimal> boardIdList=boardDao.getAllBoardId(Boolean.FALSE);
		// 其中key用于存储板块ID，value用于存储BOARD_DATE和FIVE_DAY_RATE两个字段
		Map<BigDecimal,List> boardIndexFiveDayRateMap=new HashMap<BigDecimal,List>();
		// 用于存储BOARD_INDEX表中FIVE_DAY_RATE字段
		List fiveDayRateList=null;
		// 用于存储各个板块某段时间以内的数据
		double[][] data=new double[boardIdList.size()][5];
		// 用于存储所有板块的ID
		String[] boardId = new String[boardIdList.size()];
		String[] column = {""};
		// 将各个板块在某段时间之内的数据封装至boardIndexFiveDayRateMap
		for(int i=0;i<boardIdList.size();i++){
			fiveDayRateList=boardIndexDao.getFiveDayRate(beginDate, endDate, boardIdList.get(i).toString());
			boardIndexFiveDayRateMap.put(new BigDecimal(boardIdList.get(i).longValue()), fiveDayRateList);
		}
		// 将各个板块的数据填充至data
		for(int i=0;i<boardIdList.size();i++){
			for(int j=0;j<fiveDayRateList.size();j++){
				data[i][j]=Double.parseDouble(boardIndexFiveDayRateMap.get(new BigDecimal(boardIdList.get(i).longValue())).get(j).toString());
			}
		}
		// 将各个板块的ID填充至boardId
		for(int i=0;i<boardId.length;i++){
			Iterator iterator=(Iterator) boardIndexFiveDayRateMap.keySet().iterator();
			while(iterator.hasNext()){
				boardId[i]=String.valueOf(iterator.next());
			}
		}
		
		CategoryDataset dataset = DatasetUtilities.createCategoryDataset(boardId, column, data);
		JFreeChart chart = ChartFactory.createBarChart3D("水果销量统计图", "水果", "销量",
				dataset, PlotOrientation.VERTICAL, true, false, false);
		
		try {
			FileOutputStream fos = new FileOutputStream(PICTURE_PATH+"test/"+beginDate+"-"+endDate+PICTURE_FORMAT);
			// 将统计图标输出成JPG文件
			ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
					1, // JPEG图片的质量，0~1之间
					chart, // 统计图标对象
					1800, // 宽
					1000,// 宽
					null // ChartRenderingInfo 信息
					);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 实验图表
	 */
	@SuppressWarnings({ "rawtypes", "deprecation" })
	public void testPicture(){
		String beginDate="20150101";
		String endDate="20150601";
		String boardId="4";
		
		List fiveDayRateList=boardIndexDao.getFiveDayRate(beginDate, endDate, boardId);
		List tenDayRateList=boardIndexDao.getTenDayRate(beginDate, endDate, boardId);
		
		JFreeChart jfreechart;

		TimeSeries fiveDayRateSeries = new TimeSeries("Board Index - Five Day Rate",org.jfree.data.time.Day.class);
		TimeSeries tenDayRateSeries = new TimeSeries("Board Index - Ten Day Rate",org.jfree.data.time.Day.class);
		TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
		
		for (int i = 0; i < fiveDayRateList.size(); i++) {
			Object[] object=(Object[]) fiveDayRateList.get(i);
			int year = DateUtil.getYearFromDate(((Date)object[0]));
			int month = DateUtil.getMonthFromDate(((Date)object[0]));
			int day = DateUtil.getDateFromDate(((Date)object[0]));
			fiveDayRateSeries.add(new Day(day, month, year),Double.parseDouble(object[1].toString()));
		}
		
		for (int i = 0; i < tenDayRateList.size(); i++) {
			Object[] object=(Object[]) tenDayRateList.get(i);
			int year = DateUtil.getYearFromDate(((Date)object[0]));
			int month = DateUtil.getMonthFromDate(((Date)object[0]));
			int day = DateUtil.getDateFromDate(((Date)object[0]));
			tenDayRateSeries.add(new Day(day, month, year),Double.parseDouble(object[1].toString()));
		}
		
		timeSeriesCollection.addSeries(fiveDayRateSeries);
		timeSeriesCollection.addSeries(tenDayRateSeries);

		jfreechart = ChartFactory.createTimeSeriesChart("Board Index - Five Day Rate", 
				"Date","Five Day Rate", timeSeriesCollection, true, true, true);
		jfreechart.setBackgroundPaint(Color.white);
		XYPlot xyplot = (XYPlot) jfreechart.getPlot();
		xyplot.setBackgroundPaint(Color.lightGray);
		xyplot.setDomainGridlinePaint(Color.white);
		xyplot.setRangeGridlinePaint(Color.white);
		xyplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));
		xyplot.setDomainCrosshairVisible(true);
		xyplot.setRangeCrosshairVisible(true);
		org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot.getRenderer();
		if (xyitemrenderer instanceof XYLineAndShapeRenderer) {
			XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer;
			xylineandshaperenderer.setBaseShapesVisible(true);
			xylineandshaperenderer.setBaseShapesFilled(true);
		}
		DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
		dateaxis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

		try {
			FileOutputStream fos = new FileOutputStream(PICTURE_PATH+"test/"+beginDate+"-"+endDate+PICTURE_FORMAT);
			// 将统计图标输出成JPG文件
			ChartUtilities.writeChartAsJPEG(fos, // 输出到哪个输出流
					1, // JPEG图片的质量，0~1之间
					jfreechart, // 统计图标对象
					1800, // 宽
					1000,// 宽
					null // ChartRenderingInfo 信息
					);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
